package com.sangeng.exception;

import com.sangeng.domain.response.RespBean;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常配置
 */
//控制器的增强类，如果发生异常，并且符合类中自定义的拦截异常类的时候，就会被拦截
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(SQLException.class)
    public RespBean mySqlException(SQLException e){
        if (e instanceof SQLIntegrityConstraintViolationException){
            return RespBean.error("该数据有关联，操作失败");
        }
        return RespBean.error("数据库操作失败");
    }
    @ExceptionHandler(RuntimeException.class)
    public RespBean Exception(RuntimeException e){
        String[] split = e.toString().split(":");
        if (split.length>1){
            return RespBean.error(split[1]);
        }
        return RespBean.error(e.toString());
    }
}
